import threading
import getchlib


def get_key_thread(callback, live=None):
    def func():

        try:
            while True:
                sequence = getchlib.getkey()
                if sequence == '\x1b':
                    sequences = sequence + getchlib.getkey() + getchlib.getkey()
                elif sequence == 'à':
                    getchlib.getkey()
                    continue
                else:
                    sequences = sequence

                callback(sequences)
                if live is not None:
                    try:
                        live.refresh()
                    except BlockingIOError:
                        pass
        except Exception as e:
            import traceback
            with open('error.log', 'a') as f:
                f.write(traceback.format_exc())

    thread = threading.Thread(target=func)

    return thread


def get_hotkey_thread(callbacks=None):
    def func():
        hotkey_listener = getchlib.HotKeyListener()
        for key, func in callbacks.items():
            hotkey_listener.add_hotkey(key, func)
        hotkey_listener.daemon = True
        hotkey_listener.start()

    return threading.Thread(target=func)


def get_key_sequence():
    return getchlib.getkey()


def is_current_process_in_foreground(window_name):
    import pygetwindow as gw
    # 检查传递的窗口名称是否与当前激活的窗口名称一致，用来检查当前程序是否是前台程序
    return gw.getActiveWindow() == window_name


if __name__ == '__main__':
    is_current_process_in_foreground()
    # while True:
    #     s = Getch()
    #     print('{:02x}'.format(ord(s)))
